package com.lz.springboot.apollo.datasource;
import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

@Configuration
@MapperScan(basePackages = "com.lz.springboot.apollo.jdbc.dao", sqlSessionTemplateRef  = "wlwSqlSessionTemplate")
public class DataSourceConfigWlw {

    @Bean(name = "wlwDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.wlw")
    @Primary
    public DataSource wlwDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "wlwSqlSessionFactory")
    @Primary
    public SqlSessionFactory wlwSqlSessionFactory(@Qualifier("wlwDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:mybatis/mybatis-config-wlw.xml"));
        return bean.getObject();
    }

    @Bean(name = "wlwTransactionManager")
    @Primary
    public DataSourceTransactionManager wlwTransactionManager(@Qualifier("wlwDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "wlwSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate wlwSqlSessionTemplate(@Qualifier("wlwSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}